const { member, manager } = require('../models/index')
const _ = require('lodash')
const uuidv5 = require('uuid/v5')
const bcrypt = require('bcrypt')
const moment = require('moment')
const errorHelper = require('../util/errorHelper')
const tokenGenerator = require('../util/tokenGenerator')

class MemberController {
  // constructor() {}

  async createMember(memberDetail) {
    const { name, phone, recommendId, settleId, password, creditCard, creditImg, position } = memberDetail

    if (await this.checkExist({ phone })) {
      throw errorHelper(400, 'account duplicate')
    }
    // 根据邮箱生成memberId
    const memberId = `member-${uuidv5(phone, uuidv5.URL)}`
    // 通过用户提交的密码生成身份验证字符串
    const salt = bcrypt.genSaltSync(this.saltSounds)
    const credential = bcrypt.hashSync(password, salt)
    // 创建member
    const memberInfo = {
      memberId,
      name,
      phone,
      recommendId,
      settleId,
      password,
      credential,
      creditCard,
      creditImg,
      position
    }
    const newMember = await member.create(memberInfo)
    if (!newMember) {
      throw errorHelper(400, 'account duplicate')
    }
    const result = await this.login(phone, password)
    return result
  }

  async login(phone, password, device, ip) {
    const mInfo = await this.checkExist({ phone })
    if (!mInfo) {
      throw errorHelper(400, 'account or password error')
    }
    const mId = mInfo.memberId
    if (!bcrypt.compareSync(password, mInfo.credential)) {
      throw errorHelper(400, 'account or password error')
    }
    const loginTime = moment()
    const outdateTime = moment().add(12, 'h')
    const loginToken = tokenGenerator.generate(mId, 10)
    const result = await member.update(
      { token: loginToken, loginTime, outdateTime, device: device || '', ip: ip || '' },
      { where: { memberId: mId } }
    )
    return { token: loginToken, memberId: mId }
  }

  async checkTokenValid(token) {
    const memberRes = await member.findOne({
      where: { token, outdateTime: { $gt: moment() } }
    })
    if (!memberRes) {
      throw errorHelper(400, 'token outdate', 1001)
    }
    return memberRes
  }

  async upsertMember(memberData) {
    const result = await member.upsert(memberData)
    return result
  }

  async delete(members) {
    const promiseArr = []
    _.forEach(members, (item) => {
      promiseArr.push(member.update({ disable: true }, { where: item }))
    })
    return Promise.all(promiseArr).then((data) => {
      return true
    })
  }

  static async findByKind(kindId) {
    await member.findAll({ where: { kindId } })
  }

  async getMembers() {
    const members = await member.findAll({})
    if (!members.length) {
      throw errorHelper(500, 'server error')
    }
    return members
  }
  async getMemberByKey(where) {
    const memberRes = await member.findOne({ where })
    if (!memberRes) {
      throw errorHelper(400, 'field error')
    }
    return memberRes
  }
  async count() {
    const count = await member.count()
    return count
  }

  async checkExist(info) {
    const isExist = await member.findOne({ where: info })
    if (isExist && isExist.memberId) {
      return isExist
    }
    return false
  }
}
module.exports = new MemberController()
